package com.che.libcommon.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public abstract class LazyFragment extends BaseFragment {

  private boolean hasLoaded = false;

  private boolean isCreated = false;

  private View view;

  @Nullable
  @Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    if (view == null){
      view = inflater.inflate(getLayoutId(), container, false);
      initViews(view, savedInstanceState);
      isCreated = true;
      lazyLoad(this.view, savedInstanceState);
    }
    return view;
  }

  protected abstract int getLayoutId();


  protected void initViews(View view, @Nullable Bundle savedInstanceState) {

  }

  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    lazyLoad(view, null);
  }

  private void lazyLoad(View view, Bundle savedInstanceState) {
   if (!isCreated){
     return;
   }
   if (getUserVisibleHint() && !hasLoaded){
     lazyLoad();
     hasLoaded = true;
   }
    //hasLoaded = true;//注：关键步骤，确保数据只加载一次
  }

  protected abstract void lazyLoad();

  @Override
  public void onDestroyView() {
    super.onDestroyView();
    isCreated = false;
    hasLoaded = false;
  }

}
